import React from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import TextField from 'material-ui/TextField';
import $ from 'jquery';

export default class MyRegisterDialog extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            email: '',
            pass: '',
            passRepeat: '',
        }

        this.handleChange = this.handleChange.bind(this)
        this.handleRegister = this.handleRegister.bind(this)
    }

    handleRegister() {
        // alert('Register:' +
        //     ' email=' + this.state.email +
        //     ' pass=' + this.state.pass +
        //     ' passRepeat=' + this.state.passRepeat
        // )
        this.props.handleClose()

        if(this.state.pass !== this.state.passRepeat){
            alert('两次输入的密码不同')
            return
        }

        $.ajax({
            url: '/api/regUser',
            method: 'POST',
            data: {
                Email: this.state.email,
                PasswordHash: this.state.pass,
            }
        }).then(res => {
            console.log('注册结果: '+JSON.stringify(res))
            if(res.IsOk){
                alert('注册成功')
            }
        },err => {
            alert('服务器响应出错')
        })
    }

    handleChange(e) {
        const t = e.target
        const name = t.name

        this.setState({
            [name]: t.value
        })
    }

    render() {
        const actions = [
            <FlatButton
                label="取消"
                primary={true}
                onClick={this.props.handleClose}
            />,
            <FlatButton
                label="Register"
                primary={true}
                // keyboardFocused={true}
                onClick={this.handleRegister}
            />,
        ];

        return (
            <Dialog
                title="Register"
                actions={actions}
                modal={false}
                open={this.props.open}
                contentStyle={{width: '350px'}}
                onRequestClose={this.props.handleClose}>

                <TextField
                    value={this.state.email}
                    hintText="Please enter email"
                    name="email"
                    onChange={this.handleChange}
                    floatingLabelText="Email"/>

                <TextField
                    value={this.state.pass}
                    hintText="Please enter password"
                    name="pass"
                    onChange={this.handleChange}
                    floatingLabelText="Password"/>

                <TextField
                    value={this.state.passRepeat}
                    hintText="Please repeat password"
                    name="passRepeat"
                    onChange={this.handleChange}
                    floatingLabelText="Repeat"/>

            </Dialog>
        );
    }
}